<template>
  <div id="NetworkElement">
    <a-row :gutter="16">
      <a-col :span="10">
        <div class="card">
          <a-card
            title="网元结构展示"
            :tab-list="tabList"
            :active-tab-key="tabKey"
            @tabChange="(key) => onTabChange(key, 'key')"
            :bordered="false"
            style="width: 100%; min-height: 72vh"
          >
            <template #extra>
              <a-space>
                <a-upload :before-upload="uploadFile" :show-upload-list="false">
                  <a-button
                    type="primary"
                    size="small"
                    style="font-size: 12px; background-color: #f9a65d"
                  >
                    <upload-outlined></upload-outlined>
                    文件上传
                  </a-button>
                </a-upload>

                <a-button
                  type="primary"
                  size="small"
                  @click="addElement"
                  style="font-size: 12px"
                >
                  <template #icon>
                    <PlusCircleOutlined />
                  </template>
                  添加
                </a-button>
                <a-checkbox v-model:checked="isOnMap" style="font-size: 12px">
                  图
                </a-checkbox>
                <a-button
                  v-if="tabKey === 'demand'"
                  size="small"
                  type="primary"
                  :disabled="demandList.length === 0"
                  danger
                  @click="toPlan"
                  style="font-size: 14px"
                >
                  规划业务>
                </a-button>
                <a-button
                  v-if="tabKey === 'link'"
                  size="small"
                  type="primary"
                  @click="startSingleQuery"
                  style="font-size: 12px"
                >
                  单纤轮询
                </a-button>
                <a-button
                  v-if="tabKey === 'link'"
                  size="small"
                  type="primary"
                  @click="startDoubleQuery"
                  style="font-size: 12px"
                >
                  双纤轮询
                </a-button>
              </a-space>
            </template>
            <template #title>
              <div style="font-weight: bolder; font-size: 24px">项目列表</div>
            </template>

            <!-- 链路tab的子tab结构 -->
            <div v-if="tabKey === 'link'" style="margin-bottom: 16px">
              <a-tabs v-model:activeKey="currentNet" @change="onNetChange">
                <a-tab-pane key="NETONE" tab="网一">
                  <a-tabs
                    v-model:activeKey="currentLayer"
                    @change="onLayerChange"
                  >
                    <a-tab-pane key="FIBER" tab="FIBER" />
                    <a-tab-pane key="WDM" tab="WDM" />
                    <a-tab-pane key="SDH" tab="SDH" />
                    <a-tab-pane key="OTN" tab="OTN" />
                  </a-tabs>
                </a-tab-pane>
                <a-tab-pane key="NETTWO" tab="网二">
                  <a-tabs
                    v-model:activeKey="currentLayer"
                    @change="onLayerChange"
                  >
                    <a-tab-pane key="FIBER" tab="FIBER" />
                    <a-tab-pane key="WDM" tab="WDM" />
                    <a-tab-pane key="SDH" tab="SDH" />
                    <a-tab-pane key="OTN" tab="OTN" />
                  </a-tabs>
                </a-tab-pane>
              </a-tabs>
            </div>

            <a-table
              :columns="tableColumns"
              :data-source="tableList"
              :pagination="{ pageSize: 5 }"
              :scroll="{ x: 400 }"
            >
              <template #bodyCell="{ column, record }">
                <template
                  v-if="column.key === 'nodeName' || column.key === 'name'"
                >
                  <a @click="selectElement(record)">
                    {{ record.nodeName || record.name }}
                  </a>
                </template>

                <template v-else-if="column.key === 'action'">
                  <a-space>
                    <EditOutlined
                      style="color: #015a60"
                      @click="updateElement(record)"
                    />
                    <DeleteOutlined
                      style="color: red"
                      @click="delElement(record)"
                    />
                  </a-space>
                </template>
              </template>
            </a-table>
          </a-card>
        </div>
      </a-col>
      <a-col :span="14">
        <div class="map">
          <Map :view-config="mapConfig" :event-config="eventConfig"></Map>
          <!--          <MyMap></MyMap>-->
        </div>
      </a-col>
    </a-row>

    <!-- 添加轮询结果展示 -->
    <a-row v-if="singleQueryData || doubleQueryData" :gutter="16" style="margin-top: 16px">
      <a-col :span="24">
        <a-tabs v-model:activeKey="activeQueryTab">
          <a-tab-pane key="single" tab="单纤轮询结果" v-if="singleQueryData">
            <QueryResult :query-data="singleQueryData" query-type="single" />
          </a-tab-pane>
          <a-tab-pane key="double" tab="双纤轮询结果" v-if="doubleQueryData">
            <QueryResult :query-data="doubleQueryData" query-type="double" />
          </a-tab-pane>
        </a-tabs>
      </a-col>
    </a-row>

    <a-drawer
      :width="300"
      title="详情信息"
      placement="left"
      :open="drawerOpen"
      @close="onClose"
    >
      {{ selectedElement }}
    </a-drawer>
    <a-modal v-model:open="nodeAddOpen" title="节点信息" :footer="null">
      <a-form
        :model="tempNode"
        name="basic"
        :label-col="{ span: 6 }"
        :wrapper-col="{ span: 16 }"
        autocomplete="off"
        @finish="handleElementAddOk"
      >
        <a-form-item
          label="节点名称"
          name="nodeName"
          :rules="[{ required: true, message: '请输入项目名称!' }]"
        >
          <a-input v-model:value="tempNode.nodeName" />
        </a-form-item>

        <a-form-item
          label="经度"
          name="longitude"
          :rules="[{ required: true, message: '请输入节点经度!' }]"
        >
          <a-input-number
            style="width: 100%"
            v-model:value="tempNode.longitude"
          />
        </a-form-item>

        <a-form-item
          label="纬度"
          name="latitude"
          :rules="[{ required: true, message: '请输入节点纬度!' }]"
        >
          <a-input-number
            style="width: 100%"
            v-model:value="tempNode.latitude"
          />
        </a-form-item>

        <a-form-item :wrapper-col="{ offset: 8, span: 16 }">
          <a-button type="primary" html-type="submit">提交信息</a-button>
        </a-form-item>
      </a-form>
    </a-modal>

    <a-modal v-model:open="fiberAddOpen" title="fiber信息" :footer="null">
      <a-form
        :model="tempFiber"
        name="basic"
        :label-col="{ span: 6 }"
        :wrapper-col="{ span: 16 }"
        autocomplete="off"
        @finish="handleElementAddOk"
      >
        <a-form-item
          label="头节点名称"
          name="nodeHeadName"
          :rules="[{ required: true, message: '请输入头节点名称!' }]"
        >
          <a-select
            ref="select"
            v-model:value="tempFiber.nodeHeadName"
            style="width: 100%"
            :options="nodeStore.nodeNameListSelect"
          />
        </a-form-item>

        <a-form-item
          label="尾节点名称"
          name="nodeTailName"
          :rules="[{ required: true, message: '请输入尾节点名称!' }]"
        >
          <a-select
            ref="select"
            v-model:value="tempFiber.nodeTailName"
            style="width: 100%"
            :options="nodeStore.nodeNameListSelect"
          />
        </a-form-item>

        <a-form-item
          label="纤芯数量"
          name="fiberCoreNum"
          :rules="[{ required: true, message: '请输入纤芯数量!' }]"
        >
          <a-input-number
            style="width: 100%"
            v-model:value="tempFiber.fiberCoreNum"
          />
        </a-form-item>

        <a-form-item
          label="长度"
          name="length"
          :rules="[{ required: true, message: '请输入节点长度!' }]"
        >
          <a-input-number
            style="width: 100%"
            v-model:value="tempFiber.length"
          />
        </a-form-item>

        <a-form-item :wrapper-col="{ offset: 8, span: 16 }">
          <a-button type="primary" html-type="submit">提交信息</a-button>
        </a-form-item>
      </a-form>
    </a-modal>

    <a-modal v-model:open="wdmAddOpen" title="wdm信息" :footer="null">
      <a-form
        :model="tempWDM"
        name="basic"
        :label-col="{ span: 6 }"
        :wrapper-col="{ span: 16 }"
        autocomplete="off"
        @finish="handleElementAddOk"
      >
        <a-form-item
          label="头节点名称"
          name="nodeHeadName"
          :rules="[{ required: true, message: '请输入头节点名称!' }]"
        >
          <a-select
            ref="select"
            v-model:value="tempWDM.nodeHeadName"
            style="width: 100%"
            :options="nodeStore.nodeNameListSelect"
          />
        </a-form-item>

        <a-form-item
          label="尾节点名称"
          name="nodeTailName"
          :rules="[{ required: true, message: '请输入尾节点名称!' }]"
        >
          <a-select
            ref="select"
            v-model:value="tempWDM.nodeTailName"
            style="width: 100%"
            :options="nodeStore.nodeNameListSelect"
          />
        </a-form-item>

        <a-form-item
          label="长度"
          name="length"
          :rules="[{ required: true, message: '请输入长度!' }]"
        >
          <a-input-number style="width: 100%" v-model:value="tempWDM.length" />
        </a-form-item>

        <a-form-item
          label="波长数量"
          name="waveLengthNumOne"
          :rules="[{ required: true, message: '请输入波长数量!' }]"
        >
          <a-input-number
            style="width: 100%"
            v-model:value="tempWDM.waveLengthNumOne"
          />
        </a-form-item>

        <a-form-item
          label="带宽"
          name="waveLengthBandWidthOne"
          :rules="[{ required: true, message: '请输入带宽!' }]"
        >
          <a-input-number
            style="width: 100%"
            v-model:value="tempWDM.waveLengthBandWidthOne"
          />
        </a-form-item>

        <a-form-item :wrapper-col="{ offset: 8, span: 16 }">
          <a-button type="primary" html-type="submit">提交信息</a-button>
        </a-form-item>
      </a-form>
    </a-modal>

    <a-modal v-model:open="sdhAddOpen" title="SDH信息" :footer="null">
      <a-form
        :model="tempSDH"
        name="basic"
        :label-col="{ span: 6 }"
        :wrapper-col="{ span: 16 }"
        autocomplete="off"
        @finish="handleElementAddOk"
      >
        <a-form-item
          label="头节点名称"
          name="nodeHeadName"
          :rules="[{ required: true, message: '请输入头节点名称!' }]"
        >
          <a-select
            ref="select"
            v-model:value="tempSDH.nodeHeadName"
            style="width: 100%"
            :options="nodeStore.nodeNameListSelect"
          />
        </a-form-item>

        <a-form-item
          label="尾节点名称"
          name="nodeTailName"
          :rules="[{ required: true, message: '请输入尾节点名称!' }]"
        >
          <a-select
            ref="select"
            v-model:value="tempSDH.nodeTailName"
            style="width: 100%"
            :options="nodeStore.nodeNameListSelect"
          />
        </a-form-item>

        <a-form-item
          label="长度"
          name="length"
          :rules="[{ required: true, message: '请输入长度!' }]"
        >
          <a-input-number style="width: 100%" v-model:value="tempSDH.length" />
        </a-form-item>

        <a-form-item
          label="带宽"
          name="bandwidth"
          :rules="[{ required: true, message: '请输入带宽!' }]"
        >
          <a-input-number
            style="width: 100%"
            v-model:value="tempSDH.bandwidth"
          />
        </a-form-item>

        <a-form-item :wrapper-col="{ offset: 8, span: 16 }">
          <a-button type="primary" html-type="submit">提交信息</a-button>
        </a-form-item>
      </a-form>
    </a-modal>

    <a-modal v-model:open="otnAddOpen" title="OTN信息" :footer="null">
      <a-form
        :model="tempOTN"
        name="basic"
        :label-col="{ span: 6 }"
        :wrapper-col="{ span: 16 }"
        autocomplete="off"
        @finish="handleElementAddOk"
      >
        <a-form-item
          label="头节点名称"
          name="nodeHeadName"
          :rules="[{ required: true, message: '请输入头节点名称!' }]"
        >
          <a-select
            ref="select"
            v-model:value="tempOTN.nodeHeadName"
            style="width: 100%"
            :options="nodeStore.nodeNameListSelect"
          />
        </a-form-item>

        <a-form-item
          label="尾节点名称"
          name="nodeTailName"
          :rules="[{ required: true, message: '请输入尾节点名称!' }]"
        >
          <a-select
            ref="select"
            v-model:value="tempOTN.nodeTailName"
            style="width: 100%"
            :options="nodeStore.nodeNameListSelect"
          />
        </a-form-item>

        <a-form-item
          label="长度"
          name="length"
          :rules="[{ required: true, message: '请输入长度!' }]"
        >
          <a-input-number style="width: 100%" v-model:value="tempOTN.length" />
        </a-form-item>

        <a-form-item
          label="带宽"
          name="bandwidth"
          :rules="[{ required: true, message: '请输入带宽!' }]"
        >
          <a-input-number
            style="width: 100%"
            v-model:value="tempOTN.bandwidth"
          />
        </a-form-item>

        <a-form-item :wrapper-col="{ offset: 8, span: 16 }">
          <a-button type="primary" html-type="submit">提交信息</a-button>
        </a-form-item>
      </a-form>
    </a-modal>

    <a-modal v-model:open="demandAddOpen" title="业务信息" :footer="null">
      <a-form
        :model="tempDemand"
        name="basic"
        :label-col="{ span: 6 }"
        :wrapper-col="{ span: 16 }"
        autocomplete="off"
        @finish="handleElementAddOk"
      >
        <a-form-item
          label="业务名称"
          name="name"
          :rules="[{ required: true, message: '请输入业务名称!' }]"
        >
          <a-input v-model:value="tempDemand.name" />
        </a-form-item>
        <a-form-item
          label="头节点名称"
          name="demandHead"
          :rules="[{ required: true, message: '请输入头节点名称!' }]"
        >
          <a-select
            ref="select"
            v-model:value="tempDemand.demandHead"
            style="width: 100%"
            :options="nodeStore.nodeNameListSelect"
          />
        </a-form-item>

        <a-form-item
          label="尾节点名称"
          name="demandTail"
          :rules="[{ required: true, message: '请输入尾节点名称!' }]"
        >
          <a-select
            ref="select"
            v-model:value="tempDemand.demandTail"
            style="width: 100%"
            :options="nodeStore.nodeNameListSelect"
          />
        </a-form-item>

        <a-form-item
          label="业务层级"
          name="layer"
          :rules="[{ required: true, message: '请输入业务层级!' }]"
        >
          <a-select
            v-model:value="tempDemand.layer"
            style="width: 100%"
            :options="layerSelectList"
          />
        </a-form-item>

        <a-form-item
          label="业务类型"
          name="demandType"
          :rules="[{ required: true, message: '请输入业务类型!' }]"
        >
          <a-input v-model:value="tempDemand.demandType" />
        </a-form-item>

        <a-form-item
          label="保护方式"
          name="protect"
          :rules="[{ required: true, message: '请输入保护方式!' }]"
        >
          <a-input v-model:value="tempDemand.protect" />
        </a-form-item>

        <a-form-item
          label="带宽"
          name="width"
          :rules="[{ required: true, message: '请输入节点长度!' }]"
        >
          <a-input-number
            style="width: 100%"
            v-model:value="tempDemand.width"
          />
        </a-form-item>

        <a-form-item :wrapper-col="{ offset: 8, span: 16 }">
          <a-button type="primary" html-type="submit">提交信息</a-button>
        </a-form-item>
      </a-form>
    </a-modal>
  </div>
</template>

<script setup>
import Map from "../components/Map.vue";
import useProject from "../store/project";
import useNode from "../store/node";
import useFiber from "../store/fiber.js";
import useSDH from "../store/sdh.js";
import useOTN from "../store/otn.js";
import { onMounted, ref, watch } from "vue";
import {
  EditOutlined,
  DeleteOutlined,
  PlusCircleOutlined,
  UploadOutlined,
} from "@ant-design/icons-vue";
import nodeColumns from "./columns/NodeColumns.js";
import fiberColumns from "./columns/FiberColumns.js";
import wdmColumns from "./columns/WDMColumns.js";
import sdhColumns from "./columns/SDHColumns.js";
import otnColumns from "./columns/OTNColumns.js";
import demandColumns from "./columns/DemandColumns.js";
import { fromLonLat, toLonLat } from "ol/proj";
import { storeToRefs } from "pinia";
import { layerSelectList } from "./constantArr/SelectListConstant.js";
import useWDM from "../store/wdm.js";
import useDemand from "../store/demand.js";
import { useRouter } from "vue-router";
import { message } from "ant-design-vue";
import { Service } from "../requests/services/Service.ts"; // OpenLayers的投影转换函数，用于经纬度坐标和投影坐标之间的转换
import QueryResult from '../components/QueryResult.vue';

const router = useRouter();

const projectStore = useProject();
const nodeStore = useNode();
const fiberStore = useFiber();
const wdmStore = useWDM();
const sdhStore = useSDH();
const otnStore = useOTN();
const demandStore = useDemand();
const { currentProject } = storeToRefs(projectStore);
const drawerOpen = ref(false);
const selectedElement = ref({});
const isOnMap = ref(false);

// 新的tab结构
const tabList = [
  {
    key: "node",
    tab: "节点",
  },
  {
    key: "link",
    tab: "链路",
  },
  {
    key: "demand",
    tab: "业务",
  },
];

// 当前选择的网络和层级
const currentNet = ref("NETONE");
const currentLayer = ref("FIBER");
const linkList = ref([]);

const onClose = () => {
  drawerOpen.value = false;
};

//临时网元
const tempNode = ref({
  nodeName: "",
  longitude: 0,
  latitude: 0,
});

const tempLine = ref([]);

const tempFiber = ref({
  name: "",
  fiberCoreNum: 144,
  nodeHeadName: "",
  nodeTailName: "",
  length: 100,
});

const tempWDM = ref({
  name: "",
  nodeHeadName: "",
  nodeTailName: "",
  length: 100,
  waveLengthBandWidthOne: 1000,
  waveLengthNumOne: 10,
});

const tempSDH = ref({
  name: "",
  nodeHeadName: "",
  nodeTailName: "",
  length: 100,
  bandwidth: 155,
});

const tempOTN = ref({
  name: "",
  nodeHeadName: "",
  nodeTailName: "",
  length: 100,
  bandwidth: 10000,
});

const tempDemand = ref({
  name: "",
  demandHead: "",
  demandTail: "",
  layer: "WDM",
  demandType: "",
  protect: "1+1",
  width: 10,
});

//网元添加界面
const nodeAddOpen = ref(false);
const fiberAddOpen = ref(false);
const wdmAddOpen = ref(false);
const sdhAddOpen = ref(false);
const otnAddOpen = ref(false);
const demandAddOpen = ref(false);

const mapConfig = {
  // fromLonLat是一个函数，用于将经纬度坐标转换为地图的坐标系统。
  center: fromLonLat([106.5275417, 29.55511937]), //地图中心点
  zoom: 5, // 缩放级别
  projection: "EPSG:3857",
  minZoom: 6, // 最小缩放级别
  maxZoom: 12, // 最大缩放级别
  constrainResolution: true, // 因为存在非整数的缩放级别，所以设置该参数为true来让每次缩放结束后自动缩放到距离最近的一个整数级别，这个必须要设置，当缩放在非整数级别时地图会糊
};

const tabKey = ref("node");
const actionType = ref("add");
const tableColumns = ref(nodeColumns);
const { nodeList } = storeToRefs(nodeStore);
const { fiberList } = storeToRefs(fiberStore);
const { wdmList } = storeToRefs(wdmStore);
const { otnList } = storeToRefs(otnStore);
const { sdhList } = storeToRefs(sdhStore);
const { demandList } = storeToRefs(demandStore);

const eventConfig = {
  clickEvent: (e) => {
    console.log("点击地图ee", e);
    if (isOnMap.value) {
      actionType.value = "add";
      const currentTabKey =
        tabKey.value === "link"
          ? currentLayer.value.toLowerCase()
          : tabKey.value;
      switch (currentTabKey) {
        case "node": {
          nodeAddOpen.value = true;
          tempNode.value.longitude = e[0].toFixed(2);
          tempNode.value.latitude = e[1].toFixed(2);
          break;
        }
        case "fiber": {
          if (tempLine.value.length < 2) {
            let flag = 0;
            for (let city of nodeList.value) {
              if (
                Math.abs(city.longitude - e[0]) < 0.1 &&
                Math.abs(city.latitude - e[1]) < 0.1
              ) {
                flag = 1;
                message.success("添加点" + city.nodeName + "成功");
                tempLine.value.push(city);
                break;
              }
            }
            if (flag === 0) {
              message.error("未找到节点");
            }
            if (tempLine.value.length === 2) {
              tempFiber.value.nodeHeadName = tempLine.value[0].nodeName;
              tempFiber.value.nodeTailName = tempLine.value[1].nodeName;
              fiberAddOpen.value = true;
              tempLine.value = [];
            }
            break;
          }
        }
        case "wdm": {
          if (tempLine.value.length < 2) {
            let flag = 0;
            for (let city of nodeList.value) {
              if (
                Math.abs(city.longitude - e[0]) < 0.1 &&
                Math.abs(city.latitude - e[1]) < 0.1
              ) {
                flag = 1;
                message.success("添加点" + city.nodeName + "成功");
                tempLine.value.push(city);
                break;
              }
            }
            if (flag === 0) {
              message.error("未找到节点");
            }
            if (tempLine.value.length === 2) {
              tempWDM.value.nodeHeadName = tempLine.value[0].nodeName;
              tempWDM.value.nodeTailName = tempLine.value[1].nodeName;
              wdmAddOpen.value = true;
              tempLine.value = [];
            }
            break;
          }
        }
        case "sdh": {
          if (tempLine.value.length < 2) {
            let flag = 0;
            for (let city of nodeList.value) {
              if (
                Math.abs(city.longitude - e[0]) < 0.1 &&
                Math.abs(city.latitude - e[1]) < 0.1
              ) {
                flag = 1;
                message.success("添加点" + city.nodeName + "成功");
                tempLine.value.push(city);
                break;
              }
            }
            if (flag === 0) {
              message.error("未找到节点");
            }
            if (tempLine.value.length === 2) {
              tempSDH.value.nodeHeadName = tempLine.value[0].nodeName;
              tempSDH.value.nodeTailName = tempLine.value[1].nodeName;
              sdhAddOpen.value = true;
              tempLine.value = [];
            }
            break;
          }
        }
        case "otn": {
          if (tempLine.value.length < 2) {
            let flag = 0;
            for (let city of nodeList.value) {
              if (
                Math.abs(city.longitude - e[0]) < 0.1 &&
                Math.abs(city.latitude - e[1]) < 0.1
              ) {
                flag = 1;
                message.success("添加点" + city.nodeName + "成功");
                tempLine.value.push(city);
                break;
              }
            }
            if (flag === 0) {
              message.error("未找到节点");
            }
            if (tempLine.value.length === 2) {
              tempOTN.value.nodeHeadName = tempLine.value[0].nodeName;
              tempOTN.value.nodeTailName = tempLine.value[1].nodeName;
              otnAddOpen.value = true;
              tempLine.value = [];
            }
            break;
          }
        }
        case "demand": {
          if (tempLine.value.length < 2) {
            let flag = 0;
            for (let city of nodeList.value) {
              if (
                Math.abs(city.longitude - e[0]) < 0.1 &&
                Math.abs(city.latitude - e[1]) < 0.1
              ) {
                flag = 1;
                message.success("添加点" + city.nodeName + "成功");
                tempLine.value.push(city);
                break;
              }
            }
            if (flag === 0) {
              message.error("未找到节点");
            }
            if (tempLine.value.length === 2) {
              tempDemand.value.demandHead = tempLine.value[0].nodeName;
              tempDemand.value.demandTail = tempLine.value[1].nodeName;
              demandAddOpen.value = true;
              tempLine.value = [];
            }
            break;
          }
        }
      }
    }
  },
};

const tableList = ref([]);

// 查询链路数据
const queryLinkData = async () => {
  try {
    console.log("查询链路数据参数:", {
      projectName: currentProject.value.name,
      layer: currentLayer.value,
      net: currentNet.value,
    });
    const response = await Service.queryLinkUsingGet(
      currentProject.value.name,
      currentLayer.value,
      currentNet.value
    );
    console.log("查询链路数据响应:", response.data);
    linkList.value = response.data || [];
    return response.data || [];
  } catch (error) {
    console.error("查询链路数据失败:", error);
    message.error("查询链路数据失败");
    return [];
  }
};

// 网络切换处理
const onNetChange = async (net) => {
  currentNet.value = net;
  if (tabKey.value === "link") {
    const data = await queryLinkData();
    tableList.value = data;
  }
};

// 层级切换处理
const onLayerChange = async (layer) => {
  currentLayer.value = layer;
  if (tabKey.value === "link") {
    const data = await queryLinkData();
    tableList.value = data;
    console.log("tableList.value", tableList.value);

    // 根据层级设置对应的表格列
    if (layer === "FIBER") {
      tableColumns.value = fiberColumns;
    } else if (layer === "WDM") {
      tableColumns.value = wdmColumns;
    } else if (layer === "SDH") {
      tableColumns.value = sdhColumns;
    } else if (layer === "OTN") {
      tableColumns.value = otnColumns;
    }
  }
};

onMounted(async () => {
  // 根据当前标签页加载对应的数据
  if (tabKey.value === "node") {
    tableList.value = await nodeStore.getNodeList(currentProject.value.name);
  } else if (tabKey.value === "link") {
    const data = await queryLinkData();
    tableList.value = data;
  } else if (tabKey.value === "demand") {
    tableList.value = await demandStore.getDemandList(
      currentProject.value.name
    );
  }

  // 预加载其他数据（不影响当前显示）
  await fiberStore.getFiberList(currentProject.value.name, currentNet.value);
  await wdmStore.getWDMList(currentProject.value.name, currentNet.value);
  await otnStore.getOTNList(currentProject.value.name, currentNet.value);
  await sdhStore.getSDHList(currentProject.value.name, currentNet.value);
  await demandStore.getDemandList(currentProject.value.name);
});

//标签页改变
const onTabChange = async (value, type) => {
  console.log(value, type);
  tabKey.value = value;

  if (value === "node") {
    console.log("新值node:", value);
    tableColumns.value = nodeColumns;
    // 重新获取节点数据确保数据最新
    tableList.value = await nodeStore.getNodeList(currentProject.value.name);
    console.log("tableList", tableList.value);
  } else if (value === "link") {
    console.log("新值link:", value);
    // 查询当前选择的网络和层级的链路数据
    const data = await queryLinkData();
    tableList.value = data;
    // 根据当前层级设置表格列
    if (currentLayer.value === "FIBER") {
      tableColumns.value = fiberColumns;
    } else if (currentLayer.value === "WDM") {
      tableColumns.value = wdmColumns;
    } else if (currentLayer.value === "SDH") {
      tableColumns.value = sdhColumns; 
    } else if (currentLayer.value === "OTN") {
      tableColumns.value = otnColumns;
    }
  } else if (value === "demand") {
    console.log("新值demand:", value);
    tableColumns.value = demandColumns;
    // 重新获取需求数据确保数据最新
    tableList.value = await demandStore.getDemandList(
      currentProject.value.name
    );
  }
  console.log("tableList", tableList.value);
};

//去规划
const toPlan = () => {
  router.push({ path: "/Plan" });
};
//添加网元
const addElement = () => {
  actionType.value = "add";
  if (tabKey.value === "node") {
    nodeAddOpen.value = true;
  } else if (tabKey.value === "link") {
    // 根据当前选择的层级打开对应的添加窗口
    if (currentLayer.value === "FIBER") {
      fiberAddOpen.value = true;
    } else if (currentLayer.value === "WDM") {
      wdmAddOpen.value = true;
    } else if (currentLayer.value === "SDH") {
      sdhAddOpen.value = true;
    } else if (currentLayer.value === "OTN") {
      otnAddOpen.value = true;
    }
  } else if (tabKey.value === "demand") {
    demandAddOpen.value = true;
  }
  // console.log('addElement')
};

//文件上传
const uploadFile = async (file) => {
  console.log(
    "上传文件 - 当前tab:",
    tabKey.value,
    "当前层级:",
    currentLayer.value
  );
  if (tabKey.value === "node") {
    tableList.value = await nodeStore.uploadNodeFile(
      file,
      currentProject.value.name
    );
    console.log("节点上传完成，tableList:", tableList.value);
  } else if (tabKey.value === "link") {
    // 根据当前选择的层级上传对应的文件
    if (currentLayer.value === "FIBER") {
      const uploadResult = await fiberStore.uploadFiberFile(
        file,
        currentProject.value.name,
        currentNet.value
      );
      console.log("Fiber上传结果:", uploadResult);
    } else if (currentLayer.value === "WDM") {
      const uploadResult = await wdmStore.uploadWDMFile(
        file,
        currentProject.value.name,
        currentNet.value
      );
      console.log("WDM上传结果:", uploadResult);
    } else if (currentLayer.value === "SDH") {
      const uploadResult = await sdhStore.uploadSDHFile(
        file,
        currentProject.value.name,
        currentNet.value
      );
      console.log("SDH上传结果:", uploadResult);
    } else if (currentLayer.value === "OTN") {
      const uploadResult = await otnStore.uploadOTNFile(
        file,
        currentProject.value.name,
        currentNet.value
      );
      console.log("OTN上传结果:", uploadResult);
    }
    // 上传后重新查询链路数据
    console.log("开始重新查询链路数据...");
    const data = await queryLinkData();
    tableList.value = data;
    console.log("链路数据查询完成，tableList:", tableList.value);
  } else if (tabKey.value === "demand") {
    tableList.value = await demandStore.uploadDemandFile(
      file,
      currentProject.value.name
    );
    console.log("需求上传完成，tableList:", tableList.value);
  }
  return false;
};

const headers = {
  authorization: "authorization-text",
};
//选择网元
const selectElement = (e) => {
  // console.log('selectElement',e)
  selectedElement.value = e;
  drawerOpen.value = true;
};

//删除网元
const delElement = async (e) => {
  // console.log('delElement',e)
  if (tabKey.value === "node") {
    tableList.value = await nodeStore.delSingleNode(
      currentProject.value.name,
      e.nodeName
    );
  } else if (tabKey.value === "link") {
    // 根据当前选择的层级删除对应的数据
    if (currentLayer.value === "FIBER") {
      tableList.value = await fiberStore.delSingleFiber(
        currentProject.value.name,
        e.name
      );
    } else if (currentLayer.value === "WDM") {
      tableList.value = await wdmStore.delSingleWDM(
        currentProject.value.name,
        e.name
      );
    } else if (currentLayer.value === "SDH") {
      // SDH删除逻辑，暂时使用fiber的删除方法
      tableList.value = await fiberStore.delSingleFiber(
        currentProject.value.name,
        e.name
      );
    } else if (currentLayer.value === "OTN") {
      tableList.value = await otnStore.delSingleOTN(
        currentProject.value.name,
        e.name
      );
    }
    // 删除后重新查询链路数据
    const data = await queryLinkData();
    tableList.value = data;
  } else if (tabKey.value === "demand") {
    tableList.value = await demandStore.delSingleDemand(
      currentProject.value.name,
      e.name
    );
  }
  console.log("deleteElement", tableList.value);
};

//更新网元
const updateElement = async (e) => {
  actionType.value = "update";
  if (tabKey.value === "node") {
    nodeAddOpen.value = true;
    tempNode.value = e;
  } else if (tabKey.value === "link") {
    // 根据当前选择的层级打开对应的更新窗口
    if (currentLayer.value === "FIBER") {
      fiberAddOpen.value = true;
      tempFiber.value = e;
    } else if (currentLayer.value === "WDM") {
      wdmAddOpen.value = true;
      tempWDM.value = e;
    } else if (currentLayer.value === "SDH") {
      sdhAddOpen.value = true;
      tempSDH.value = e;
    } else if (currentLayer.value === "OTN") {
      otnAddOpen.value = true;
      tempOTN.value = e;
    }
  } else if (tabKey.value === "demand") {
    demandAddOpen.value = true;
    tempDemand.value = e;
  }
  // console.log('updateElement',e)
};

//提交网元信息
const handleElementAddOk = async (e) => {
  let res;
  if (tabKey.value === "node") {
    if (actionType.value === "add") {
      res = await nodeStore.addSingleNode(
        currentProject.value.name,
        tempNode.value
      );
    } else if (actionType.value === "update") {
      res = await nodeStore.updateSingleNode(
        currentProject.value.name,
        tempNode.value.id,
        tempNode.value
      );
    }
    // console.log("handleElementAddOk",res)
    tableList.value = res;
    nodeAddOpen.value = false;
  } else if (tabKey.value === "link") {
    // 根据当前层级处理不同类型的链路数据
    if (currentLayer.value === "FIBER") {
      if (actionType.value === "add") {
        res = await fiberStore.addSingleFiber(
          currentProject.value.name,
          tempFiber.value,
          currentNet.value
        );
      } else if (actionType.value === "update") {
        res = await fiberStore.updateSingleFiber(
          currentProject.value.name,
          tempFiber.value,
          currentNet.value
        );
      }
      fiberAddOpen.value = false;
    } else if (currentLayer.value === "WDM") {
      if (actionType.value === "add") {
        res = await wdmStore.addSingleWDM(
          currentProject.value.name,
          tempWDM.value,
          currentNet.value
        );
      } else if (actionType.value === "update") {
        res = await wdmStore.updateSingleWDM(
          currentProject.value.name,
          tempWDM.value,
          currentNet.value
        );
      }
      wdmAddOpen.value = false;
    } else if (currentLayer.value === "SDH") {
      if (actionType.value === "add") {
        // SDH添加逻辑，暂时使用fiber的添加方法
        res = await fiberStore.addSingleFiber(
          currentProject.value.name,
          tempSDH.value,
          currentNet.value
        );
      } else if (actionType.value === "update") {
        // SDH更新逻辑，暂时使用fiber的更新方法
        res = await fiberStore.updateSingleFiber(
          currentProject.value.name,
          tempSDH.value,
          currentNet.value
        );
      }
      sdhAddOpen.value = false;
    } else if (currentLayer.value === "OTN") {
      if (actionType.value === "add") {
        res = await otnStore.addSingleOTN(
          currentProject.value.name,
          tempOTN.value,
          currentNet.value
        );
      } else if (actionType.value === "update") {
        res = await otnStore.updateSingleOTN(
          currentProject.value.name,
          tempOTN.value,
          currentNet.value
        );
      }
      otnAddOpen.value = false;
    }
    // 操作完成后重新查询链路数据
    const data = await queryLinkData();
    tableList.value = data;
    console.log("handleElementAddOk", res);
  } else if (tabKey.value === "demand") {
    if (actionType.value === "add") {
      res = await demandStore.addSingleDemand(
        currentProject.value.name,
        tempDemand.value
      );
    } else if (actionType.value === "update") {
      res = await demandStore.updateSingleDemand(
        currentProject.value.name,
        tempDemand.value
      );
    }
    console.log("handleElementAddOk", res);
    tableList.value = res;
    demandAddOpen.value = false;
  }
};

// 添加轮询相关的状态
const singleQueryData = ref(null);
const doubleQueryData = ref(null);
const activeQueryTab = ref('single');

// 单纤轮询
const startSingleQuery = async () => {
  try {
    const res = await Service.singleQueryUsingGet(currentProject.value.name);
    if (res.respCode === 200) {
      singleQueryData.value = res.data;
      activeQueryTab.value = 'single';
      message.success('单纤轮询完成');
    } else {
      message.error(res.message || '单纤轮询失败');
    }
  } catch (error) {
    console.error('单纤轮询错误:', error);
    message.error('单纤轮询失败');
  }
};

// 双纤轮询
const startDoubleQuery = async () => {
  try {
    const res = await Service.doubleQueryUsingGet(currentProject.value.name);
    if (res.respCode === 200) {
      doubleQueryData.value = res.data;
      activeQueryTab.value = 'double';
      message.success('双纤轮询完成');
    } else {
      message.error(res.message || '双纤轮询失败');
    }
  } catch (error) {
    console.error('双纤轮询错误:', error);
    message.error('双纤轮询失败');
  }
};
</script>

<style scoped>
.card {
  background: rgba(236, 236, 236, 0.5);
  padding: 10px;
  min-height: 75vh;
}
.map {
  min-height: 50vh;
  height: 100%;
  background: rgba(236, 236, 236, 0.5);
  padding: 10px;
}
</style>
